package com.example.wangzh.mytest.part.buchheim_algorithm;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import com.example.wangzh.mytest.part.walker_algorithm.TreePositioner;

public class BuchheimTreeView extends View {
    private TreeLayout.Node root;
    private Paint nodePaint;
    private Paint linePaint;
    private Paint textPaint;

    public BuchheimTreeView(Context context) {
        super(context);
        init();
    }

    public BuchheimTreeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        // 初始化节点画笔
        nodePaint = new Paint();
        nodePaint.setColor(Color.BLUE);
        nodePaint.setStyle(Paint.Style.FILL);
        nodePaint.setAntiAlias(true);

        // 初始化连接线画笔
        linePaint = new Paint();
        linePaint.setColor(Color.BLACK);
        linePaint.setStrokeWidth(3);
        linePaint.setAntiAlias(true);

        // 初始化文本画笔
        textPaint = new Paint();
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(24);
        textPaint.setAntiAlias(true);
    }

    public void setTree(TreeLayout.Node root) {
        this.root = root;
        invalidate(); // 触发重绘
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (root != null) {
            drawTree(canvas, root);
        }
    }

    private void drawTree(Canvas canvas, TreeLayout.Node node) {
        // 计算节点的矩形区域
        float left = (float) (node.getXCoord() - node.getLeftSize());
        float top = (float) node.getYCoord();
        float right = (float) (node.getXCoord() + node.getRightSize());
        float bottom = (float) (node.getYCoord() + 80);
        RectF rect = new RectF(left, top, right, bottom);

        // 绘制节点
        canvas.drawRect(rect, nodePaint);

        // 绘制节点坐标
        String coordinates = String.format("%s (%.1f, %.1f)", node.getName(),
                node.getXCoord(), node.getYCoord());
        float textX = left + 10; // 文本起始位置
        float textY = top + 40; // 文本垂直居中
        canvas.drawText(coordinates, textX, textY, textPaint);

        // 绘制连接线到子节点
        TreeLayout.Node child = node.getFirstChild();
        while (child != null) {
            float childX = (float) child.getXCoord();
            float childY = (float) child.getYCoord();
            canvas.drawLine((float) node.getXCoord(), (float) node.getYCoord() + 40, childX, childY,
                    linePaint);
            drawTree(canvas, child);
            child = child.getRightSibling();
        }
    }
}
